package com.gt.web.srv.auth;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.gt.web.api.exception.BusinessException;
import com.gt.web.srv.users.UserDto;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.security.Principal;

/**
 * All rights Reserved, Designed By www.vipthink.cn
 *
 * @Title: cc.foodism.foodism.star.api.auth Jwt
 * @Description: TDO 描述....
 * @author: Lee.Li
 * @date: 2022/3/13
 * @Copyright: www.xxoo.cn Inc. All rights reserved.
 * 注意：本内容仅限于食物主义内部传阅，禁止外泄以及用于其他的商业目
 */
@Setter
@Getter
@Component
public class JwtInfo implements Principal {

    private UserDto userDto;


    /**
     * Returns the name of this principal.
     *
     * @return the name of this principal.
     */
    @Override
    public String getName() {
        return userDto.getName();
    }


    public static JwtInfo parse(String token) {
        JwtInfo tokenInfo = new JwtInfo();
        try {
            String decodeStr = Base64.decodeStr(token);
            UserDto userDto = JSONUtil.toBean(decodeStr, new TypeReference<UserDto>() {
            }, true);
            tokenInfo.setUserDto(userDto);
        }
        catch (Exception e) {
            throw new BusinessException(600,"解析token异常:"+token);
        }
        return tokenInfo;
    }

    public static UserDto auth() {
        JwtInfo tokenInfo = (JwtInfo) SecurityContextHolder.getContext().getAuthentication().getCredentials();
        return tokenInfo.getUserDto();
    }
}
